# -*- coding: utf-8 -*-
import random
import time
from threading import Lock

from spider import BaseTranslate

# DeepL语言选项
deepl_lang = {
    'auto': '检测源语言',
    'zh': '中文（简体）',
    'en': '英语',
    'de': '德语',
    'id': '印尼语',
    'fr': '法语',
    'es': '西班牙语',
    'it': '意大利语',
    'nl': '荷兰语',
    'pl': '波兰语',
    'ru': '俄语',
    'pt': '葡萄牙语',
    'tr': '土耳其语',
    'ja': '日语',
    'bg': '保加利亚语',
    'hr': '克罗地亚语',
    'cs': '捷克语',
    'da': '丹麦语',
    'et': '爱沙尼亚语',
    'fi': '芬兰语',
    'el': '希腊语',
    'hu': '匈牙利语',
    'is': '冰岛语',
    'ga': '爱尔兰语',
    'lv': '拉脱维亚语',
    'lt': '立陶宛语',
    'mt': '马耳他语',
    'no': '挪威语',
    'ro': '罗马尼亚语',
    'sk': '斯洛伐克语',
    'sl': '斯洛文尼亚语',
    'sv': '瑞典语'
}


class DeepLTranslate(BaseTranslate):
    """DeepL爬虫"""
    _lock = Lock()
    _instance = None
    _init_flag = False

    def __new__(cls, *args, **kwargs):
        with cls._lock:
            if cls._instance is None:
                cls._instance = object.__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._init_flag:  # 只初始化一次
            super(DeepLTranslate, self).__init__()
            # 请求一下DeepL以更新客户端的cookies
            self._get('https://www.deepl.com/translator')
            # 标记初始化完成
            self._init_flag = True

    def _get_lan(self, query):
        """查询语言种类"""
        url = 'https://www2.deepl.com/jsonrpc?method=LMT_split_text'
        form_data = {
            'jsonrpc': '2.0',
            'method': 'LMT_split_text',
            'params': {
                'texts': [query],
                'commonJobParams': {'mode': 'translate'},
                'lang': {
                    'lang_user_selected': 'auto',
                    'preference': {
                        'weight': {},  # TODO: translator_late.min.$c56d68.js -- getLanguagePreference
                        'default': 'default'
                    }
                }
            },
            'id': int(1e4 * round(1e4 * random.random())) + 5
        }
        response = self._post(url, json=form_data)
        data = response.json()
        return data['result']['lang']['detected']

    @staticmethod
    def _get_form_data(query, from_lan, to_lan):
        """构建表单数据"""
        form_data = {
            'jsonrpc': '2.0',
            'method': 'LMT_handle_jobs',
            'params': {
                'jobs': [{
                    'kind': 'default',
                    'sentences': [{
                            'text': query,
                            'id': 0,
                            'prefix': ''
                        }],
                    'raw_en_context_before': [],
                    'raw_en_context_after': [],
                    'preferred_num_beams': 4
                }],
                'lang': {
                    'preference': {
                        'weight': {},
                        'default': 'default'
                    },
                    'source_lang_user_selected': from_lan,
                    'target_lang': to_lan
                },
                'priority': 1,
                'commonJobParams': {
                    'mode': 'translate',
                    'browserType': 1
                },
                'timestamp': int(time.time() * 1000)
            },
            'id': int(1e4 * round(1e4 * random.random())) + 4
        }
        return form_data

    def translate(self, query, from_lan, to_lan, *args, **kwargs):
        """ 启动翻译

        :param query: 翻译内容
        :param from_lan: 源语言
        :param to_lan: 目标语言
        :return:
        """
        # if from_lan == 'auto':
        #     from_lan = self._get_lan(query)
        if from_lan == to_lan:
            to_lan = 'en' if from_lan == 'zh' else 'zh'
        # 获取译文
        url = 'https://www2.deepl.com/jsonrpc?method=LMT_handle_jobs'
        form_data = self._get_form_data(query, from_lan, to_lan)
        response = self._post(url, json=form_data)
        data = response.json()
        text_list = [item['sentences'][0]['text'] for item in data['result']['translations'][0]['beams']]
        print(text_list)

    def get_translation(self, *args, **kwargs):
        """ 获取译文
        ["hello", ["", ""]]
        """
        pass

    def get_explanation(self, *args, **kwargs):
        """ 获取释义
        [{
            "explains": [
                {
                    "part": "int.",
                    "means": [
                        ["喂，你好（用于问候或打招呼）；喂，你好（打电话时的招呼语）；喂，你好（引起别人注意的招呼语）", "", False]
                    ]
                },
                {
                    "part": "n.",
                    "means": [
                        ["招呼，问候；（Hello）（法、印、美、俄）埃洛（人名）", "", False]
                    ]
                }
            ]
        }]
        """
        pass

    def get_sentence(self, *args, **kwargs):
        """ 获取例句 """
        return list()

    def get_tts(self, text, lan, *args, **kwargs):
        """ 获取发音 """
        return bytes()


if __name__ == '__main__':
    dt = DeepLTranslate()
    dt.translate('hello', 'en', 'zh')
